package com.dong.ui.component;

import com.dong.ui.util.ImageUtils;
import lombok.Data;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @description:
 * @author: 陈瑞东
 * @create: 2021-08-26 16:01
 */
@Data
public class IconPanel extends JPanel {

    private static final int DEFAULT_WIDTH = 100; // 图标默认宽度
    private static final int DEFAULT_HEIGHT = 100; // 图标默认高度

    private String id;
    public String text;
    public ImageIcon icon;

    public IconPanel(String text, ImageIcon icon) {
        this.text = text;
        this.icon = icon;
        setSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
        init();
    }

    public IconPanel(String id, String text, ImageIcon icon, Dimension preferredSize) {
        this.id = id;
        this.text = text;
        this.icon = icon;
        setSize(preferredSize);
        init();
    }

    /**
     * 初始化控件
     */
    private void init() {
        this.setOpaque(false);

        handlerView();
        handlerEvent();
    }

    /**
     * 处理事件
     */
    private void handlerEvent() {
        // 鼠标事件
        mouseActionEvent();
    }

    /**
     * 处理显示
     */
    private void handlerView() {
        // 设置布局格式
        this.setLayout(new BorderLayout());


        // 上方图标大小
        int topHeight = this.getHeight() / 4 * 3;
        int topWidth = this.getWidth() / 4 * 3;


        // 下方文字大小
        int bottomHeight = this.getHeight() / 4 * 1;
        int bottomWidth = this.getWidth();


        // 上方内容
        JLabel top = new JLabel();
        top.setHorizontalAlignment(SwingConstants.CENTER);
        top.setPreferredSize(new Dimension(topWidth, topHeight));
//        icon.setImage(icon.getImage().getScaledInstance(topWidth, topHeight, Image.SCALE_DEFAULT));//图片自适应窗口大小
        icon = ImageUtils.scaleImage(icon, topWidth, topHeight);//图片自适应窗口大小
        top.setIcon(icon);
        // 下方内容
        JLabel bottom = new JLabel(text, SwingConstants.CENTER);
        bottom.setHorizontalAlignment(SwingConstants.CENTER);
        bottom.setPreferredSize(new Dimension(bottomWidth, bottomHeight));

        this.add(top, BorderLayout.NORTH);
        this.add(bottom);
    }

    /**
     * 鼠标事件
     */
    private void mouseActionEvent() {
        Color color = this.getBackground();
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                // 悬浮时，修改背景色
                setBackground(new Color(216, 230, 242));
                setOpaque(true);
                super.mouseEntered(e);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                // 离开时，还原背景色
                setOpaque(false);
                setBackground(color);
                super.mouseExited(e);
            }
        });
    }

}
